import { defineStore } from 'pinia';
import { Session } from '/@/utils/storage';
import request from '/@/utils/request';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		userInfos: {
			user:{},
			authPageList: [] as string[],
			authBtnList: [] as string[],
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			} else {
				const userInfos = <UserInfos>await this.getApiUserInfo();
				this.userInfos = userInfos;
			}
		},
		async getApiUserInfo() {
			return new Promise((resolve) => {
				setTimeout(async () => {
					await request.get('/currentUser').then((res)=>{
						if(res.data && res.data.user && res.data.user.id){
							Session.set('userInfo', res.data);
							resolve(res.data);
						}
					})					
				}, 0);
			});
		},
	},
});
